package cc.facesign.admin.controller;


import cc.facesign.admin.bean.TblConf;
import cc.facesign.admin.bean.fv.confupload.ConfSimpleFv;
import cc.facesign.admin.bean.query.ConfQuery;
import cc.facesign.admin.bean.query.UserQuery;
import cc.facesign.admin.bean.vo.ConfVo;
import cc.facesign.admin.bean.vo.UserSignVo;
import cc.facesign.admin.bean.vo.UserVo;
import cc.facesign.admin.service.TblConfService;
import cc.facesign.admin.service.TblDeptService;
import cc.facesign.admin.service.TblUserService;
import cc.facesign.admin.utils.PageUtils;
import cc.facesign.admin.utils.PowerUtils;
import cc.facesign.common.exception.FacesignException;
import cc.facesign.common.utils.bean.R;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-05-06
 */
@RestController
@RequestMapping("/admin/conf")
@Api(description = "会议查询")
public class TblConfController {

    @Autowired
    private TblConfService confService;

    @Autowired
    private TblUserService userService;


    @Autowired
    private PowerUtils powerUtils;

    @Autowired
    private TblDeptService deptService;



    /**
     * 按confId查询单个会议的信息
     * 详见 cc.facesign.admin.bean.vo.ConfVo
     * @param id 会议id
     * @return
     */
    @PreAuthorize("@ex.hasAuthorith('root:exe:conf')")
    @ApiOperation("查会议信息")
    @GetMapping("/getInfoById/{id}")
    public R getInfoById(@PathVariable String id) {
        if(!powerUtils.getCurrentChildConfIdSet().contains(id)) {
            throw new FacesignException(R.ERROR, "权限异常");
        }

        ConfVo res = confService.getInfoById(id);
        return R.ok().data("data", res);
    }

    @PreAuthorize("@ex.hasAuthorith('root:exe:conf')")
    @ApiOperation("返回会议中所有用户id")
    @GetMapping("/getSimpleUsers/{confId}")
    public R getSimpleUsers(@PathVariable String confId) {
        if (!powerUtils.isConfCreater(confId) && !powerUtils.getCurrentChildConfIdSet().contains(confId)) {
            return R.error().message("权限异常");
        }

        List<String> list = confService.getUserListByConfId(confId).stream()
                .map(x -> x.getId())
                .collect(Collectors.toList());

        return R.ok().data("data", list);
    }

    /**
     * 查会议中的用户信息（条件+分页）
     * map中有效参数为：
     *      status： 签到状态“0”、“1”、“2”、“12”
     *      deptId： 父部门id（查的时候包括子部门）
     *      name： 用户名模糊查询
     * @param confId 会议id
     * @return
     */
    @PreAuthorize("@ex.hasAuthorith('root:exe:conf')")
    @ApiOperation("查会议中的用户信息【条件+分页】")
    @PostMapping("/getUserListById/{confId}/{current}/{limit}")
    public R getUserListById(@PathVariable String confId,
                             @PathVariable Integer current,
                             @PathVariable Integer limit,
                             @RequestBody(required = false) Map<String, String> map) {
        if (!powerUtils.getCurrentChildConfIdSet().contains(confId) && !powerUtils.isConfCreater(confId)) {
            throw new FacesignException(R.ERROR, "权限异常");
        }

        String status = map.get("status"); // 签到状态
        String deptId = map.get("deptId"); // 父部门id
        String name = map.get("name"); // 用户名

        UserQuery query = new UserQuery();
        if (!StringUtils.isEmpty(deptId)) {
            if (!powerUtils.getCurrentChildDeptIdSet().contains(deptId)) {
                throw new FacesignException(R.ERROR,"权限异常");
            }
            Set<String> deptIdSet = deptService.getChildIdSetByDeptId(deptId);
            query.setDeptIds(new ArrayList<>(deptIdSet));
        }
        if (name != null) query.setName(name);

        // 获取该会议中的所有用户，包括签到情况
        Set<String> querySet = userService.getInfoListByQuery(query).stream()
                .map(x -> x.getId())
                .collect(Collectors.toSet());
        List<UserVo> list = confService.getUserInfoContainsSignByConfId(confId).stream()
                .filter(x -> querySet.contains(x.getId()))
                .collect(Collectors.toList());

        // status
        if (!StringUtils.isEmpty(status)) {
            Integer isSign = Integer.parseInt(status);
            if (isSign != 12) {
                list = list.stream()
                        .filter(x -> Objects.equals(x.getIsSign(), isSign))
                        .collect(Collectors.toList());
            } else {
                list = list.stream()
                        .filter(x -> !Objects.equals(x.getIsSign(), 0))
                        .collect(Collectors.toList());
            }
        }

        IPage<UserVo> page = PageUtils.page(list, current, limit);
        return R.ok().data("page", page);
    }

    /**
     * 传入status
     * 需携带token
     * @param status
     * @return
     */
    @PreAuthorize("@ex.hasAuthorith('root:exe')")
    @ApiOperation("按status值查会议数量")
    @GetMapping("/getCountByStatus/{status}")
    public R getCountByStatus(@PathVariable Integer status) {
        HashSet<String> set = powerUtils.getCurrentChildDeptIdSet();

        int res = 0;
        for (TblConf e : confService.list(null)) {
            if (set.contains(e.getDeptId()) && status.equals(e.getStatus())) res++;
        }

        return R.ok().data("count", res);
    }

    /**
     * 只查用户所在部门下的会议
     * 查询类中的deptIds属性用户输入无效，后端根据用户权限查找用户所属部门下的所有部门会议
     * @param current 当前页
     * @param limit 每页数量
     * @param query cc.facesign.admin.bean.query.ConfQuery
     * @return page
     */
    @PreAuthorize("@ex.hasAuthorith('root:exe')")
    @ApiOperation("查会议列表【条件+分页】")
    @PostMapping("/getPageCondition/{current}/{limit}")
    public R getPageCondition(@PathVariable("current") Integer current,
                              @PathVariable("limit") Integer limit,
                              @RequestBody(required = false)ConfQuery query) {
        HashSet<String> set = powerUtils.getCurrentChildDeptIdSet();
        query.setDeptIds(new ArrayList<>(set));

        List<ConfVo> list = confService.getListByQuery(query);
        IPage<ConfVo> page = PageUtils.page(list, current, limit);
        return R.ok().data("page", page);
    }


    /**
     * 1、获取每个用户的签到信息
     * 2、获取会议总人数、未签到人数
     * 3、获取未签到用户的详情信息
     * @param id 会议id
     * @return
     *          everyont: 每个用户签到情况
     *          overall:
     *      *         total: 总人数
     *      *         sign：签到人数
     *      *         no-sign：未签到人数
     *      *         sign-userList：已签到用户信息
     *      *         no-sign-userList：未签到用户信息
     */
    @PreAuthorize("@ex.hasAuthorith('root:exe:conf')")
    @ApiOperation("查会议的签到情况")
    @GetMapping("/getUserSignListByConfId/{id}")
    public R getUserSignListByConfId(@PathVariable("id") String id) {
        // 校验
        if (!powerUtils.getCurrentChildConfIdSet().contains(id)) {
            throw new FacesignException(R.ERROR, "权限异常");
        }

        // 每个用户的签到情况
        List<UserSignVo> res =
        confService.getUserSignListByConfId(id);

        // 会议签到总情况
        Map<String, Object> map =
        confService.getConfSignInfoByConfId(id);

        return R.ok()
                .data("everyone", res) // 每个用户的签到情况
                .data("overall", map); // 总签到情况
    }




    @PreAuthorize("@ex.hasAuthorith('root:exe:conf')")
    @ApiOperation("获取会议中simple用户信息")
    @GetMapping("/getSimpleUserInfo/{confId}")
    public R getSimpleUserInfo(@PathVariable String confId) {
        if (!powerUtils.getCurrentChildConfIdSet().contains(confId) && !powerUtils.isConfCreater(confId)) {
            throw new FacesignException(R.ERROR, "权限异常");
        }

        ConfSimpleFv res = confService.getSimpleInfoAll(confId);

        return R.ok().data("data", res);
    }

}

